<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cateId" placeholder="请选择分类" size="small">
              <el-option
                v-for="obj in cateList"
                :key="obj.id"
                :label="obj.cate_name"
                :value="obj.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="choose"
              >筛选</el-button
            >
            <el-button type="info" size="small" @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button
          type="primary"
          size="small"
          class="btn-pub"
          @click="showPubDialog"
          >发表文章</el-button
        >
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="artList" style="width: 100%" border stripe>
        <el-table-column label="文章标题" prop="title">
          <template v-slot="scope">
            <el-link type="primary" @click="showDetail(scope.row.id)">
              {{ scope.row.title }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="cate_name"></el-table-column>
        <el-table-column label="发表时间" prop="pub_date">
          <template v-slot="scope">
            <span> {{ $formatDate(scope.row.pub_date) }} </span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="danger" size="mini" @click="remove(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChangeFn"
        @current-change="handleCurrentChangeFn"
        :current-page.sync="q.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size.sync="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 发布文章的对话框 -->
    <el-dialog
      title="发表文章"
      :visible.sync="pubDialogVisible"
      fullscreen
      :before-close="handleClose"
      @close="dialogClose"
    >
      <el-form
        :model="pubForm"
        :rules="pubFormRules"
        ref="pubFormRef"
        label-width="100px"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select
            v-model="pubForm.cate_id"
            placeholder="请选择分类"
            style="width: 100%"
          >
            <el-option
              v-for="obj in cateList"
              :key="obj.id"
              :label="obj.cate_name"
              :value="obj.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <quill-editor
            v-model="pubForm.content"
            @blur="contentChangeFn"
          ></quill-editor>
        </el-form-item>
        <el-form-item label="文章封面" prop="cover_img">
          <!-- 用来显示封面的图片 -->
          <img
            class="cover_img"
            src="../../assets/images/cover.jpg"
            alt=""
            ref="imgRef"
          />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input
            type="file"
            style="display: none"
            accept="image/*"
            ref="iptFileRef"
            @change="changeCoverFn"
          />
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="selCoverFn">+ 选择封面</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="pubArticle('已发布')"
            >发布</el-button
          >
          <el-button type="info" @click="pubArticle('草稿')"
            >存为草稿</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 查看文章详情对话框 -->
    <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
      <h1 class="title">{{ artDetail.title }}</h1>
      <div class="info">
        <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
        <span>发布时间：{{ $formatDate(artDetail.pub_date) }}</span>
        <span>所属分类：{{ artDetail.cate_name }}</span>
        <span>状态：{{ artDetail.state }}</span>
      </div>
      <!-- 分割线 -->
      <el-divider></el-divider>
      <img
        v-if="artDetail.cover_img"
        :src="baseURL + artDetail.cover_img"
        alt=""
      />
      <div v-html="artDetail.content" class="detail-box"></div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCategoryAPI,
  uploadArticleAPI,
  getArticalListAPI,
  getArticleInfoAPI,
  deleteArticleAPI
} from '@/api'
import { baseURL } from '@/utils/request'
import imgObj from '@/assets/images/cover.jpg'
export default {
  name: 'ArtList',
  data () {
    return {
      // 文章分类列表
      cateList: [],
      // 查询参数对象
      q: {
        pagenum: 1, // 默认拿第一页数据
        pagesize: 3, // 默认当前页需要几条数据
        cateId: '',
        state: ''
      },
      // 文章列表
      artList: [],
      // 文章总数
      total: 0,

      // 发表文章对话框
      pubDialogVisible: false,
      // 发表文章表单的数据
      pubForm: {
        title: '', // 文章标题
        cate_id: '', // 文章分类id
        content: '', // 文章内容
        cover_img: '', // 封面图
        state: '' // 发布状态(值：'已发布'、'草稿')
      },
      pubFormRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          {
            min: 1,
            max: 30,
            message: '文章标题的长度为1-30个字符',
            trigger: 'blur'
          }
        ],
        cate_id: [
          { required: true, message: '请选择文章类别', trigger: 'change' }
        ],
        content: [
          // content对应quill-editor富文本编辑器不支持el提供的表单校验
          { required: true, message: '请输入文章内容', trigger: 'change' }
        ],
        cover_img: [
          { required: true, message: '请选择封面图', trigger: 'blur' }
        ]
      },

      // 文章详情对话框
      detailVisible: false,
      // 文章详情数据
      artDetail: {},
      baseURL
    }
  },
  methods: {
    // 获取文章分类
    async getCateList () {
      const { data: res } = await getCategoryAPI()
      this.cateList = res.data
    },
    // 获取文章列表
    async getArticleList () {
      const { data: res } = await getArticalListAPI(this.q)
      this.artList = res.data
      this.total = res.total
    },
    // 筛选文章
    choose () {
      this.q.pagenum = 1
      this.getArticleList()
    },
    // 重置筛选
    reset () {
      this.q.pagenum = 1
      this.q.cateId = ''
      this.q.state = ''
      this.getArticleList()
    },
    // 改变每页显示的数量
    handleSizeChangeFn (sizes) {
      // size:当前每页显示条数
      this.q.pagesize = sizes
      this.q.pagenum = 1
      this.getArticleList()
    },
    // 当前页码改变时
    handleCurrentChangeFn (nowPage) {
      // nowPage:当前页码
      this.q.pagenum = nowPage
      this.getArticleList()
    },
    // 发表文章点击事件--->出现对话框
    showPubDialog () {
      this.pubDialogVisible = true
    },
    // 发布文章对话框关闭前的回调
    async handleClose (done) {
      // done:调用就会关闭对话框
      const confirmResult = await this.$confirm(
        '此操作将导致文章信息丢失。是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      if (confirmResult === 'cancel') return false
      done()
    },
    // 选择文章封面点击事件
    selCoverFn () {
      this.$refs.iptFileRef.click()
    },
    // 用户选择了封面图
    changeCoverFn (e) {
      const files = e.target.files
      if (files.length === 0) {
        this.pubForm.cover_img = null
        this.$refs.imgRef.setAttribute('src', imgObj)
      } else {
        this.pubForm.cover_img = files[0]
        this.$refs.imgRef.setAttribute('src', URL.createObjectURL(files[0]))
      }
      // 校验封面规则
      this.$refs.pubFormRef.validateField('cover_img')
    },
    // 富文本编辑器内容改变校验
    contentChangeFn () {
      this.$refs.pubFormRef.validateField('content')
    },
    // 表单发布文章 或 存为草稿
    pubArticle (str) {
      this.pubForm.state = str
      this.$refs.pubFormRef.validate(async (valid) => {
        if (valid) {
          const formData = new FormData() // FormData类是HTML5新出的专门为了装文件内容和其他参数的一个容器
          formData.append('title', this.pubForm.title)
          formData.append('cate_id', this.pubForm.cate_id)
          formData.append('content', this.pubForm.content)
          formData.append('cover_img', this.pubForm.cover_img)
          formData.append('state', this.pubForm.state)
          const { data: res } = await uploadArticleAPI(formData)
          // console.log(res)
          if (res.code !== 0) return this.$message.error(res.message)
          this.$message.success(res.message)
          // 关闭对话框
          this.pubDialogVisible = false
          // 重新获取文章列表
          this.getArticleList()
        } else {
          return false
        }
      })
    },
    // 新增文章对话框关闭--回调
    dialogClose () {
      this.$refs.pubFormRef.resetFields()
      // 需要手动给封面设置重置初始值
      this.$refs.imgRef.setAttribute('src', imgObj)
    },
    // 文章详情点击事件
    async showDetail (artId) {
      const { data: res } = await getArticleInfoAPI(artId)
      this.detailVisible = true
      // console.log(res)
      this.artDetail = res.data
    },
    // 删除文章
    async remove (id) {
      const { data: res } = await deleteArticleAPI(id)
      // console.log(res)
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      // 保证当最后一页只有一个数据时，删除它之后让页数减一且页数不能到0
      if (this.artList.length === 1) {
        if (this.q.pagenum > 1) {
          this.q.pagenum--
        }
      }

      this.getArticleList()
    }
  },
  created () {
    this.getCateList()
    this.getArticleList()
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}

::v-deep .ql-editor {
  min-height: 300px;
}

.cover_img {
  width: 350px;
  height: 350px;
}

.title {
  font-size: 25px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
::v-deep .detail-box {
  img {
    width: 500px;
  }
}
</style>
